package com.afdor.rws.event.channel.local.producer;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.event.Event;
import com.afdor.rws.event.channel.client.producer.AbstractEventProducer;
import com.afdor.rws.event.channel.client.producer.EventProducer;
import com.afdor.rws.event.channel.local.observer.ObserverEventSource;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * 本地事件生产者
 *
 * @author 悭梵
 * @date Created in 2018-08-08 15:21
 */
@Slf4j
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@Extension(value = "local", order = Extension.NORMAL_ORDER - 100, scope = Extension.Scope.PROTOTYPE, interfaceClass = EventProducer.class)
public class LocalEventProducer extends AbstractEventProducer {

    private ObserverEventSource eventSource;

    public LocalEventProducer(ObserverEventSource eventSource) {
        super();
        this.eventSource = Optional.ofNullable(eventSource).orElseThrow(() -> new IllegalArgumentException("事件发生管理容器为空"));
    }

    @Override
    public void destroy() {
        eventSource = null;
        super.destroy();
    }

    @Override
    public void doSendEvent(@NonNull Event event) {
        eventSource.send(Optional.ofNullable(event).orElseThrow(() -> new IllegalArgumentException("事件对象为空")));
        if (log.isDebugEnabled()) {
            log.debug("=====================>> 同步发送消息已成功");
        }
    }

}
